<?php

declare(strict_types=1);

namespace App\Model\PssModel;

use App\Model\BaseModel\BasePssModel;
use Hyperf\DbConnection\Db;
use App\Service\Code\Normal;
use App\Service\BaseService;

class Area extends BasePssModel
{
    public $table = 'area';
    
    //指定写入字段
    protected $fillable = [
        
    ];
    
    //指定字段展示类型
    protected $casts = [
    ];
    
    //获取省市区清单
    public function getRegionLists()
    {
        return self::query()
        ->select([
            Db::raw('CONCAT(area_id,"") as areaId'),
            Db::raw('area_name as areaName'),
            Db::raw('CONCAT(area_parent_id,"") as areaParentId'),
        ])
        ->orderBy('area_sort','asc')
        ->get()
        ->toArray();
    }
    
    public function getAreaListByIds( $ids = [] ){
        return self::query()
        ->select(['*'])
        ->whereIn('area_id',$ids)
        ->orderBy('area_sort','asc')
        ->get()
        ->toArray();
    }
    
    /**
     * 获取地区列表
     */
    public function getAreaList( $pid = 0 )
    {
        $cacheKey = "WEB_AREA_TREE";
        $redis = BaseService::instance()->getRedisObj();
        $redis->select(BaseService::rdb_num);
        $lists = $redis->get($cacheKey);
        if( !empty($lists) ) {
            $lists = json_decode($lists,true);
            return Normal::returnCode(Normal::SUC,"获取成功",$lists);
        }
        
        $list = self::query()
        ->select([
            'area_id',
            'area_name',
            'area_parent_id'
        ])
        ->get()
        ->toArray();
        
        $list = tree($list, 0, 'area_id', 'area_parent_id');
        //更新查询结果到缓存
        $redis->set($cacheKey,json_encode($list),BaseService::CACHE_TIME);
        return Normal::returnCode(Normal::SUC,"获取成功",$list);
    }
}